package com.fang;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SaleTicketDemo02 {
    public static void main(String[] args) {
        // 并发：多个线程操作同一个资源类, 把资源类丢入线程
        Ticket2 ticket = new Ticket2();

        // @FunctionalInterface 函数式接口
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        },"A"  ).start();

        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        },"B"  ).start();

        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        },"C"  ).start();
    }
}

// Lock
// 1.new ReentrantLock()
// 2.lock.lock()  加锁
// 3.finally ==> lock.unlock() 解锁
class Ticket2 {
    private int number = 50;

    Lock lock = new ReentrantLock();

    // 买票的方式
    public void sale() {
        // 加锁
        lock.lock();

        // lock.tryLock(); // 尝试获得锁
        try {
            // 业务代码
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了第" + (number--) + "张票，剩余" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();// 解锁
        }
    }


}
